<?php


    function formatAddress1($province)
    {
        if (strpos($province, '内蒙古自治区') !== false) {
            $province = '内蒙古自治区';
        } elseif (strpos($province, '内蒙古') !== false) {
            $province = '内蒙古自治区';
        } elseif (strpos($province, '内蒙') !== false) {
            $province = '内蒙古自治区';
        } elseif (strpos($province, '广西壮族自治区') !== false) {
            $province = '广西壮族自治区';
        } elseif (strpos($province, '广西省') !== false) {
            $province = '广西壮族自治区';
        } elseif (strpos($province, '广西') !== false) {
            $province = '广西壮族自治区';
        } elseif (strpos($province, '西藏自治区') != false) {
            $province = '西藏自治区';
        } elseif (strpos($province, '宁夏回族自治区') !== false) {
            $province = '宁夏回族自治区';
        } elseif (strpos($province, '宁夏') !== false) {
            $province = '宁夏回族自治区';
        } elseif (strpos($province, '新疆维吾尔自治区')) {
            $province = '新疆维吾尔自治区';
        } elseif (strpos($province, '新疆') !== false) {
            $province = '新疆维吾尔自治区';
        }
        return $province;
    }
    
    function formatAddressToArray($address)
    {
        if (strpos($address, '|') !== false) {
            $result =  explode("|", $address);
            if(count($result) == 4){
                return $result;
            }
        }
        if (strpos($address, '深圳市') === 0) {
            $address = '广东省' . $address;
        }
        if (strpos($address, '自治区') !== false) {
            preg_match('/(.*?(省|自治区|北京市|天津市|上海市|重庆市))/', $address, $matches);
        } else {
            preg_match('/(.*?(省|内蒙古|自治区|北京市|天津市|上海市|重庆市|内蒙|新疆|广西|西藏))/', $address, $matches);
        }
        if (count($matches) > 1) {
            $province = $matches[count($matches) - 2];
            $address = str_replace($province, '', $address);
        }
        if (in_array($province, ['北京市', '天津市', '上海市', '重庆市'])) {
            $address = $province . $address;
        }
        preg_match('/(.*?(市|自治州|地区|区划|县|盟))/', $address, $matches); //盟|旗|
        if (count($matches) > 1) {
            $city = $matches[count($matches) - 2];
            $address = str_replace($city, '', $address);
        }
        preg_match('/(.*?(市|区|县|镇|乡|街道|旗))/', $address, $matches);
        if (count($matches) > 1) {
            $area = $matches[count($matches) - 2];
            $address = str_replace($area, '', $address);
        }
        return [
            isset($province) ? formatAddress1($province) : '',
            isset($city) ? $city : '',
            isset($area) ? $area : '',
            $address,
        ];
    }